package com.kxf.utils;

import android.util.Base64;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @ProjectName: AndroidTestDemo
 * @Package: com.kxf.androidtestdemo.utils
 * @ClassName: RSAUtil
 * @Description: java类作用描述
 * @Author: kuangxuefeng
 * @qq: 1024883177
 * @CreateDate: 2020/4/10 14:31
 */
public class RSAUtil {
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    //私钥 PKCS8格式
    private static final String RSA_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDa/zyptfeG/9SHXu158gFVtaF7\n" +
            "7bVW41TKMwGl2X/AC8RDFXwZ95ALFXdvjkOEzqZbt+6d/Bksoh/K5LRVFGo7+8ju4l96NkLhRD0L\n" +
            "bz3BVCRHn19uv685T+44EKMCvgfcwGzx8Hl2iJmWHizQVgpW/CjGeXv9/H5+EL1+SG26kj8v1Xl0\n" +
            "h4OzS1l0L+PD8xmo7DE2TTutHK4S/GLUeMEtwa/JkKdeJjvFODSQfhvMrYxhYSHRN5/3zkkqSeyw\n" +
            "dAuDGjLEZKdtHHTB3ph1cdGKIEvqdM/XPEoESN+vyDR0Oz5Dsr9t51LP9WcYJSuHm3db7FBpqO7e\n" +
            "kSiLACJ1aV59AgMBAAECggEAGAWSzSfbarjBwoaYZH22BUWK3NnugAUoLhTJu7w/ndx8jwI6jmug\n" +
            "JoMYiolPoS/8wgdLOpOmXEW9WIddO47ld0ZvXDrDD9gHXofabVhqrPvyjdOux2ppyU7Z+dbjVp/r\n" +
            "I10NJj3DSQwDUtrk/gZOFIwM2faF8g6B/oiODJ3bwXDo24fvi3qfYHQ5B4Zom1JJYXJCGyhi5qzo\n" +
            "SbF/cyyfGtpeCuekZdFOE9SHtgCPURRCBa/WESStqdK2K41hup8mpP0IKOA3ABmT1Y4YwBhsSzQX\n" +
            "x8xr3anTKf/JHNy2oKapGQmO7eaI+eXf7QbkhqJW8CsZQ5iFPFXoHBUuZU5wwQKBgQDztF4mMmA/\n" +
            "sjPnWwAW9RYyFeBsieSym88Vr0kpE9Ikl5qK4HT1a45n+B9HbQbw757jGRw7baVcCJOc27oyRaKh\n" +
            "B7pfGSyRHjSl1nNJ/BueYTeEvFuK6S1bSz9NUR2lGpbCTAyMVDoU6aEzotLDxDOTfsTSamG3hWIh\n" +
            "a1Jb6htvwQKBgQDmC8CTI5fPog8/LvA/RaXZ9CcbXO7uE5kTE0nrDfgWy9HpmW4yCuP3w38Oyjtk\n" +
            "Pvn8P9xs632VB7CL35znOZS3USjtSRQ/tnye9Jv8LbXNUzgsfShDvinTOnNFTUkHuIk94ZCRJqP1\n" +
            "57kaSyfiOGlEd8bazUvw0Q4JN14hwz8dvQKBgCq74haIluAUe42CI43jBDVcKLJfq762G6YNyqJt\n" +
            "W1gXTX40xc2TQrFwjOuVbrYpDo98A7tYCrsMtfW3gfr2wwHBvSiX3XzE8y5xYF4E20L2gSnBbbv6\n" +
            "D34Gv97q7mvZMb54X2rsChNItH+9eX/ik7i1bgYHqYLo3MBHdXWwo4cBAoGAVFQKi+WISPzHSgoS\n" +
            "157YZUUy8LzoeS2F95AikJ/WScT9dfxggMetOa3YbbuEegL78JQYYXUR3AetmBiok7pv4aNGtXUM\n" +
            "jy5+EGbqp066TkIrXWOj1vFms5/Bka37D3F+HckKDat0fzgqipDyVeMH86lUo/CN3gFEe+xn/Uht\n" +
            "YqECgYBqLMtx3LERNqyA+RUF/auYC7Zmp4rorI6fwCoRg37mpkAj+wc5/yBVsLH9FfSwgHYLFaJ2\n" +
            "eSfBPrHSQm+epcUH+YyvhqGJZqoj8Ka4q0Evyc+IPerR4vvMtkRSGYP5nZ2eW7mmbOP68vV7P2VL\n" +
            "axtUdZV0yAXlnM1QqpSQSb+53Q==";
    private static final String RSA_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2v88qbX3hv/Uh17tefIBVbWhe+21VuNU\n" +
            "yjMBpdl/wAvEQxV8GfeQCxV3b45DhM6mW7funfwZLKIfyuS0VRRqO/vI7uJfejZC4UQ9C289wVQk\n" +
            "R59fbr+vOU/uOBCjAr4H3MBs8fB5doiZlh4s0FYKVvwoxnl7/fx+fhC9fkhtupI/L9V5dIeDs0tZ\n" +
            "dC/jw/MZqOwxNk07rRyuEvxi1HjBLcGvyZCnXiY7xTg0kH4bzK2MYWEh0Tef985JKknssHQLgxoy\n" +
            "xGSnbRx0wd6YdXHRiiBL6nTP1zxKBEjfr8g0dDs+Q7K/bedSz/VnGCUrh5t3W+xQaaju3pEoiwAi\n" +
            "dWlefQIDAQAB";

    public static final String KEY_ALGORITHM = "RSA";
    //public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA签名
     *
     * @param content       待签名数据
     * @return 签名值
     */
    public static byte[] sign(byte[] content) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(RSA_PRIVATE_KEY, Base64.DEFAULT));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content);
            byte[] signed = signature.sign();
            return signed;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * RSA验签名检查
     *
     * @param content       待签名数据
     * @param sign          签名值
     * @return 布尔值
     */
    public static boolean verify(byte[] content, byte[] sign) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(RSA_PUBLIC_KEY, Base64.DEFAULT);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
            signature.initVerify(pubKey);
            signature.update(content);
            boolean bverify = signature.verify(sign);
            return bverify;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    //map对象中存放公私钥
    public static Map<String, String> initKey(int keysize) throws Exception {
        //获得对象 KeyPairGenerator 参数 RSA 1024个字节
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(keysize);
        //通过对象 KeyPairGenerator 获取对象KeyPair
        KeyPair keyPair = keyPairGen.generateKeyPair();

        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //公私钥对象存入map中
        Map<String, String> keyMap = new HashMap(2);
        keyMap.put(PUBLIC_KEY, Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT));
        keyMap.put(PRIVATE_KEY,Base64.encodeToString(privateKey.getEncoded(), Base64.DEFAULT));
        System.out.println("keyMap=" + keyMap);
        return keyMap;
    }
}
